import { axiosInstance } from "@/utils/axios-utils";
import { UnifyResult, SqlSugarPagedList } from "../unifyResult";
/**
 * 此类作为普通API的基类，不继承常规的通用CRUD方法，如文件操作，服务器信息等类
 */
export class BaseNormal {
  /**
   * 服务器请求的起始路径, 类似 'http://localhost:**
   */
  protected basePath = import.meta.env.VITE_API_URL;

  /**
   * Api路径。子类通过构造函数修改, 其中api转义为具体的路径，如'/api/test'
   */
  protected apiPath = "/api/test";

  /**
   * 请求完整路径（除了方法名），类似 `http://localhost:**\/api/test`
   */
  protected baseUrl = this.basePath + this.apiPath; //

  /**
   * 定义一个axios变量，便于子类访问
   */
  protected axiosInstance = axiosInstance;

  /**
   * 构造函数，接受Api路径，如'/api/test'
   */
  constructor(apiPath: string) {
    // 构造函数
    this.apiPath = apiPath;
    this.baseUrl = this.basePath + this.apiPath;
  }
}

/**
 * 服务器请求基础类
 */
export class BaseApi<EntityType = any, AddType = any, UpdateType = any> extends BaseNormal {
  /**
   * 分页获取列表
   */
  page = async (data: object | null) => {
    const url = this.baseUrl + `/page`;
    return await this.axiosInstance.get<UnifyResult<SqlSugarPagedList<EntityType>>>(url, { params: data });
  };

  /**
   * 获取列表
   */
  list = async (data: object | null) => {
    const url = this.baseUrl + `/list`;
    return await this.axiosInstance.get<UnifyResult<Array<EntityType>>>(url, { params: data });
  };

  /**通用查询方法 */
  normalGet = async <entityType>(api: string, data: object | null) => {
    const url = this.baseUrl + api;
    return await this.axiosInstance.get<UnifyResult<entityType>>(url, { params: data });
  };

  normalGetBlob = async <entityType>(api: string, data: object | null) => {
    const url = this.baseUrl + api;
    return await this.axiosInstance.get<UnifyResult<entityType>>(url, { params: data, responseType: "blob" });
  };
  /**
   * 新增记录
   */
  add = async (data: AddType) => {
    const url = this.baseUrl + `/add`;
    return await this.axiosInstance.post<UnifyResult<void>>(url, data);
  };
  /**
   * 更新记录
   */
  update = async (data: UpdateType) => {
    const url = this.baseUrl + `/update`;
    return await this.axiosInstance.post<UnifyResult<void>>(url, data);
  };
  /**
   * 删除记录
   */
  delete = async (data: object) => {
    const url = this.baseUrl + `/delete`;
    return await this.axiosInstance.post<UnifyResult<void>>(url, data);
  };

  /** 批量删除 */
  batchDelete = async (data: object) => {
    const url = this.baseUrl + `/BatchDelete`;
    return await this.axiosInstance.post<UnifyResult<void>>(url, data);
  };

  /** Post操作通用接口 */
  normalPost = async <entityType>(api: string, data: object | null) => {
    const url = this.baseUrl + api;
    return await this.axiosInstance.post<UnifyResult<entityType>>(url, data);
  };
}
